﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Harmontronics.DataAccess.Operate.Business;
using Harmontronics.Model.Other;
using Harmontronics.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using SqlSugar;
using System.Text;

namespace Harmontronics.Api.Config
{
    /// <summary>
    /// 扩展类  
    /// </summary>
    public static class HostBuilderExtend
    {
        public static void Register(this WebApplicationBuilder builder)
        {
            //创建AutoFac容器
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

            //在容器中进行配置
            builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
            {
                //注册接口和实现层
                containerBuilder.RegisterModule(new AutofacModuleRegister());
            });

            //创建数据库上下文
            builder.Services.AddDbContext<HcDbContext>(opt =>
            {
                // opt.UseSqlite($"Data Source={Path.Combine(AppDomain.CurrentDomain.BaseDirectory, builder.Configuration.GetConnectionString("ForceMonitor_DbConnectionString"))}");
                // opt.UseMySql("Server=localhost;port=3306;uid=root;pwd=123456;database=LineMes", ServerVersion.AutoDetect("Server=localhost;port=3306;uid=root;pwd=123456;database=LineMes"));
                opt.UseMySql(builder.Configuration.GetConnectionString("MySqlConnectStr"),
                    ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("MySqlConnectStr")),
                    b => b.MigrationsAssembly("Harmontronics.Repository"));

            });
            //Automapper映射
            builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));
            //第一步，注册JWT
            builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));

            #region JWT校验

            //第二步，增加鉴权逻辑
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
             .AddJwtBearer(options =>  //这里是配置的鉴权的逻辑
             {
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                     ValidateIssuer = true,//是否验证Issuer
                     ValidateAudience = true,//是否验证Audience
                     ValidateLifetime = true,//是否验证失效时间
                     ValidateIssuerSigningKey = true,//是否验证SecurityKey
                     ValidAudience = tokenOptions.Audience,//
                     ValidIssuer = tokenOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))//拿到SecurityKey 
                 };
             });

            #endregion
            //添加跨域策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("X-Pagination"));
            });

            //设置Json返回的日期格式
            builder.Services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
        }
    }
}
